import { defineStore } from 'pinia';
import * as customerApi from '@/api/customer';
import { Message } from '@arco-design/web-vue';
import { ref } from 'vue';

const useCustomerStore = defineStore('customer', () => {
    const customers = ref<any>([])

    async function getCustomers(param?: any) {
        const response: any = await customerApi.queryCustomerList(param)
        if (response.code === 20000) {
            customers.value = response.data.customers
            return response.data.customers
        }
        return []
    }

    async function deleteCustomer(param: { id?: number }) {
        const response: any = await customerApi.deleteCustomer(param)
        if (response.code === 20000) {
            Message.success('移除成功');
        }
    }

    async function saveCustomer(param: any) {
        if (param.id) {
            await customerApi.updateCustomer(param);
        } else {
            await customerApi.createCustomer(param);
        }
        Message.success('保存成功');
    }

    async function getCustomerFollows(param?: any) {
        const response: any = await customerApi.queryCustomerFollowList(param)
        if (response.code === 20000) {
            return response.data.customerFollows
        }
        return []
    }

    async function deleteCustomerFollow(param: { id?: number }) {
        const response: any = await customerApi.deleteCustomerFollow(param)
        if (response.code === 20000) {
            Message.success('移除成功');
        }
    }

    async function saveCustomerFollow(param: any, message = true) {
        const apiCall = param.id ? customerApi.updateCustomerFollow : customerApi.createCustomerFollow;
        const response: any = await apiCall(param)
        if (response.code === 20000 && message) {
            Message.success(param.id ? '更新成功' : '创建成功');
        }
        return response.data
    }

    return { customers, getCustomers, deleteCustomer, saveCustomer, getCustomerFollows, deleteCustomerFollow, saveCustomerFollow }
});

export default useCustomerStore;
